package flex.cc.drive.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.common.utils.CommonUtils;
import flex.cc.drive.dto.DriverInterfaceLogEntity;
import flex.cc.drive.dto.DriverRemarkEntity;
import flex.cc.drive.service.DriverInterfaceLogService;
import flex.cc.drive.service.DriverRemarkService;
import flex.cc.single.dto.entity.VerifyTaskEntity;
import flex.cc.single.service.VerifyTaskService;
import flex.cc.store.dto.entity.CouponTrackEntity;
import flex.cc.store.dto.entity.StoreCouponEntity;
import flex.cc.store.dto.entity.StorePackageEntity;
import flex.cc.store.dto.vo.MsgConstant;
import flex.cc.store.service.CouponTrackService;
import flex.cc.store.service.StoreCouponService;
import flex.cc.store.service.StoreOrderService;
import flex.cc.store.service.StorePackageService;
import flex.cc.store.util.AESSingleUtil;
import flex.cc.store.util.SdSignUtil;
import flex.cc.system.entity.DictCodeEntity;
import flex.cc.system.service.DictCodeService;
import flex.cc.util.APIConfigUtil;

/**
 * 
 * @author WANGCONG
 * 2022年1月17日上午10:12:01
 * @desc 代驾核销通知上游业务实现层
 *    代驾卡券不涉及核销确认
 */
@Service
public class DriverVerifyService{
	private static final Logger logger = LoggerFactory.getLogger(DriverVerifyService.class);
	@Resource
	private StorePackageService packageService;
	@Resource
	private StoreCouponService couponService;
	@Resource
	private CouponTrackService couponTrackService;
	@Resource
	private DictCodeService dictCodeService;
	@Resource
	private StoreOrderService orderService;
	@Resource
    private DriverInterfaceLogService logService;
	@Resource
    private DriverRemarkService remarkService;
	@Resource
    private APIConfigUtil apiConfigUtil;
	@Resource
	private VerifyTaskService taskService;
	/**
	 * 
	 * @author WANGCONG
	 * 2022年1月17日上午10:02:36
	 * @desc 核销通知
	 */
	@Async
	public Map<String, String> verifyNotice(Map<String, String> postMap) {
		Map<String, String> resultMap = new HashMap<>();
		String orderNo = postMap.get("orderNo"); //代驾服务单号
		String couponNum = postMap.get("couponNum"); //卡券码
		String cardNo = postMap.get("packageCode");  //归属服务包
		if(PublicUtil.isEmpty(couponNum) || PublicUtil.isEmpty(cardNo)) {
			resultMap.put("code", "01");
			resultMap.put("msg", "参数不全");
			return resultMap;
		}
		StoreCouponEntity couponEntity = couponService.queryByCouponNum(couponNum);
		if (couponEntity == null) {
			resultMap.put("code", "01");
			resultMap.put("msg", "卡券不存在");
			return resultMap;
		}
		//变更卡券核销时间、状态为已使用
		Map<String, Object> coupon_params = new HashMap<String, Object>();
		coupon_params.put("couponNum", couponNum);
		coupon_params.put("status", "3"); // 3-已使用（核销完成）
		coupon_params.put("checkDate", new Date());
		coupon_params.put("updateTime", new Date());
		couponService.updateByParam(coupon_params);
		//判断卡券归属服务包状态，变更为已兑现
		String packageCode = couponEntity.getPackageCode();
		StorePackageEntity packageVo = packageService.queryByPackageCode(packageCode);
		if (packageVo != null) {
			Map<String, Object> package_params = new HashMap<String, Object>();
			package_params.put("packageCode", packageCode);
			package_params.put("checkDate", new Date()); //核销时间
			package_params.put("updateTime", new Date());
			if("0".equals(packageVo.getStatus())){
				package_params.put("status", "1"); //1-已兑换
			}
			packageService.updateByParam(package_params);
		}
		
		resultMap.put("code", "00");
		resultMap.put("msg", "成功");
//----------------------------------------------------------------------------------------------------------------------//
		String serviceItemCode = couponEntity.getActivityId(); //服务类型id
		Map<String, Object> body = new HashMap<String, Object>();
		String password = "";
		String sign = "";
		String specificServiceItems = "30公里酒后代驾";//服务项目名称
		long hxTime = new Date().getTime();
		Map<String, Object> codeParams = new HashMap<String, Object>();
		codeParams.put("code", serviceItemCode);
		codeParams.put("typeCode", "activityName");
		DictCodeEntity codeVo = dictCodeService.getOneByParams(codeParams);
		if(codeVo!=null){
			specificServiceItems = codeVo.getValue();
		}
		String storeUserName = apiConfigUtil.getSYApiConfig("storeUserName");
		String storePassword = apiConfigUtil.getSYApiConfig("storePassword");
		String storeKey = apiConfigUtil.getSYApiConfig("storeKey");
		String storeProTypeCode = apiConfigUtil.getSYApiConfig("storeProTypeCode");
		String storeWriteOffUrl = apiConfigUtil.getSYApiConfig("storeWriteOffUrl");
		
		try {
			cardNo = couponEntity.getPackageCodeCF();
			password = AESSingleUtil.encrypt(storePassword, storeKey);
			StringBuilder sb = new StringBuilder("");
			sb.append(storeUserName).append(password)
			  .append(storeProTypeCode).append(serviceItemCode).append(cardNo)
			  .append("1").append(hxTime);
			sign = SdSignUtil.MD5(sb.toString());
		} catch (Exception e1) {
			saveDriveRemark(orderNo,couponNum,"异常","密码加密或数字签名异常");
			saveTrack(couponEntity, "1", "上游核销通知接口失败---密码加密或数字签名异常", "0", "上游核销接口");
			return resultMap;
		}
        body.put("username", storeUserName);
        body.put("password", password);
        body.put("proTypeCode", storeProTypeCode);
        body.put("cardNo", cardNo); //父卡券号
        body.put("hxStatus", "1");
        body.put("hxTime", hxTime);
        body.put("sign", sign);
        body.put("serviceItemCode", serviceItemCode);
        body.put("specificServiceItems", specificServiceItems);
        body.put("jsPrice", ""); //结算价
        //增加子卡券信息
        body.put("isChildCoupon", "1"); //是否为子卡券，1-是
        List<HashMap<String, Object>> childCardList = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> childCard = new HashMap<String, Object>();
        childCard.put("childCardNo", couponNum); //子卡券号
        childCard.put("useCount", "1");
        childCard.put("orderId", couponEntity.getOrderId()); //订单号
        childCardList.add(childCard);
        body.put("childCardList", childCardList);
        
        String dataId = UUID.randomUUID().toString().replace("-", "");
        logger.info("---核销接口日志保存开始---dataId："+dataId);
    	DriverInterfaceLogEntity logEntity = new DriverInterfaceLogEntity();
    	logEntity.setDataId(dataId);
    	logEntity.setOrderNo(orderNo);
    	logEntity.setOrderId(couponNum);
    	logEntity.setInterfaceName("代驾核销接口");
    	String requestBody = CommonUtils.toJSONString(body);
		logEntity.setRequestTime(new Date());
		logEntity.setRequestBody(requestBody);
		
		logger.info("代驾核销通知接口url ==" + storeWriteOffUrl);
		logger.info("代驾核销通知接口请求报文 ==" + requestBody);
		
        String resultJson = CommonUtils.storePost(storeWriteOffUrl, requestBody);
        logEntity.setResponseTime(new Date());
        logEntity.setResponseBody(resultJson);
        logEntity.setCreateTime(new Date());
        logService.insert(logEntity);
        logger.info("---核销接口日志保存结束---");
        //默认成功
        //String resultJson="{\"result\":{\"errMsg\":\"第三方卡券统一核销接口调用成功！\",\"status\":\"success\"},\"resultCode\":200,\"message\":\"OK\"}";
        logger.info(couponNum+"代驾请求核销接口响应报文-->"+resultJson);
        
        String resultCode = "success";  //响应码code
        if (resultJson != null) {
        	try {
        		JSONObject json = JSONObject.parseObject(resultJson);
        		int code = Integer.valueOf(json.get("resultCode").toString());
        		if(HttpStatus.SC_OK == code){ //调用成功
        			JSONObject results = (JSONObject)json.get("result");
        			String status = results.get("status").toString();
        			if(status.equals("success")){
        		    	saveDriveRemark(orderNo,couponNum,"成功","");
        				//记录卡券轨迹
        				saveTrack(couponEntity, "1", MsgConstant.successNotice, "1", "上游核销接口");
        			}else{
        				resultCode = "error";
        				String errMsg = results.get("errMsg").toString();
        		    	saveDriveRemark(orderNo,couponNum,"失败",errMsg);
						saveTrack(couponEntity, "1", MsgConstant.errorNotice+":"+errMsg, "0", "上游核销接口");
        			}
        		}else{
        			resultCode = "error";
        			String message = json.get("message").toString();
    		    	saveDriveRemark(orderNo,couponNum,"失败",message);
        			saveTrack(couponEntity, "1", MsgConstant.errorNotice+":"+message, "0", "上游核销接口");
        		}
			} catch (Exception e) {
				resultCode = "error";
				//返回参数格式有误，解析异常，记录卡券轨迹
				saveDriveRemark(orderNo,couponNum,"异常",MsgConstant.errorResponse);
				saveTrack(couponEntity, "1", MsgConstant.errorResponse, "0", "上游核销接口");
			}
        }else{
        	resultCode = "error";
        }
        //add W 2022年4月2日14:11:22 根据核销结果，操作t_store_verify_task，定时复推上游核销通知任务---start
        VerifyTaskEntity taskVo = new VerifyTaskEntity();
        if("success".equals(resultCode)){
        	taskVo.setCouponNum(couponNum);
        	taskVo.setStatus(0); //核销结果：0-成功、1-失败
        	taskVo.setUpdateTime(new Date());
        	taskService.update(taskVo);
        }else{
        	//核销失败，根据卡券码判断t_store_verify_task中是否已存在，若不存在，则插入
        	Map<String, Object> task_params = new HashMap<String, Object>();
        	task_params.put("couponNum", couponNum);
        	VerifyTaskEntity vo = taskService.getOneByParams(task_params);
        	if(PublicUtil.isEmpty(vo)){
        		taskVo.setCouponNum(couponNum);
        		taskVo.setWriteOffUrl(storeWriteOffUrl);
        		taskVo.setCardType("1");//1-服务包到店、2-服务包代驾、3-单项到店、4-单项代驾、5-健康护理
        		taskVo.setRequestBody(CommonUtils.toJSONString(body));
        		taskVo.setResponseBody(resultJson);
        		taskVo.setStatus(1); //核销结果：0-成功、1-失败
        		taskVo.setCreateTime(new Date());
        		taskService.insert(taskVo);
        	}
        }
        //add W 2022年4月2日14:11:22 根据核销结果，操作t_store_verify_task，定时复推上游核销通知任务---end
        
		return resultMap;
	}
	
	//trackType-轨迹类型：0-车服内部，1-与上游交互，2-与下游交互，3-与商户端交互
	public void saveTrack(StoreCouponEntity couponEntity, String trackType, String trackDesc, String result, String creater){
		Date d = new Date();
        CouponTrackEntity vo = new CouponTrackEntity(couponEntity.getId(),couponEntity.getCouponNum(),
        		trackType,trackDesc,couponEntity.getStatus(),result);
        vo.setIsDelete(0);
		vo.setCreateTime(d);
        vo.setCreater(creater);
        vo.setUpdateTime(d);
        vo.setUpdater(creater);
		couponTrackService.insert(vo);
	}
	
	
	public void saveDriveRemark(String orderNo,String couponNum,String status,String errMsg){
		String remarkDataId = UUID.randomUUID().toString().replace("-", "");
    	DriverRemarkEntity driverRemarkEntity = new DriverRemarkEntity();
    	driverRemarkEntity.setDataId(remarkDataId);
    	driverRemarkEntity.setOrderNo(orderNo);
    	driverRemarkEntity.setOrderId(couponNum);
    	driverRemarkEntity.setStatus("1");
    	if(status.equals("成功")){
    		driverRemarkEntity.setLink("代驾核销接口，状态："+status);
    		driverRemarkEntity.setRemark("代驾核销成功");
    	}else if(status.equals("失败")){
    		driverRemarkEntity.setRemark("代驾核销失败");
    		driverRemarkEntity.setLink("代驾核销接口，状态："+status+"，失败原因："+ errMsg);
    	}else {
    		driverRemarkEntity.setLink("代驾核销接口，状态："+status+"，"+ errMsg);
    		driverRemarkEntity.setRemark("代驾核销异常");
    	}
    	driverRemarkEntity.setCreateTime(new Date());
    	driverRemarkEntity.setCreator("system");
    	driverRemarkEntity.setUpdateTime(new Date());
    	driverRemarkEntity.setUpdater("system");
    	driverRemarkEntity.setIsDelete(0);
    	remarkService.insert(driverRemarkEntity);
	}

}
